package com.example.demo.generator.config;

import com.example.demo.generator.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@WebFilter(filterName = "tokenfilter",urlPatterns = "/success/*")
public class TokenFilter implements Filter {
    @Autowired
    public JwtUtil jwtUtil;

    String ORIGIN = "Origin";

    //这里配置不过滤的路径，支持模糊查询
    private static final String NOT_FILTER_STR = "/login|/doc.html|swagger|.ico|.js|.css|/v2/api-docs|webjars";
    private static List<String> NOTFILTER_ARRAY;

    public TokenFilter() {
        NOTFILTER_ARRAY = Arrays.asList(NOT_FILTER_STR.split("\\|"));
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        String origin = httpRequest.getHeader(ORIGIN);

        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,token");
        httpResponse.setHeader("Access-Control-Expose-Headers", "*");
        //filterChain.doFilter(httpRequest, httpResponse);

        Map<String,String> map = new HashMap<>();
        String url =  ((HttpServletRequest)servletRequest).getRequestURI();
        boolean isNotLogin = false;
        for (String str : NOTFILTER_ARRAY) {
            isNotLogin = url.contains(str);
            if (isNotLogin) {
                break;
            }
        }
        if(url != null){
            //登录请求直接放行
            //if("/user/login".equals(url)){
            if(isNotLogin){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }else{
                //其他请求验证token
                String token = ((HttpServletRequest)servletRequest).getHeader("token");
                if(StringUtils.isNotBlank(token)){
                    //token验证结果
                    int verify  = jwtUtil.verify(token);
                    if(verify != 1){
                        //验证失败
                        if(verify == 2){
                            map.put("code","-1");
                            map.put("errorMsg","token已过期");
                        }else if(verify == 0){
                            map.put("code","-2");
                            map.put("errorMsg","用户信息验证失败");
                        }
                    }else if(verify  == 1){
                        //验证成功，放行
                        filterChain.doFilter(servletRequest,servletResponse);
                        return;
                    }
                }else{
                    //token为空的返回
                    map.put("code","-3");
                    map.put("errorMsg","未携带token信息");
                }
            }
            JSONObject jsonObject = new JSONObject(map);
            servletResponse.setContentType("application/json");
            //设置响应的编码
            servletResponse.setCharacterEncoding("utf-8");
            //响应
            PrintWriter pw=servletResponse.getWriter();
            pw.write(jsonObject.toString());
            pw.flush();
            pw.close();
        }
    }
}
